import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  UploadedFile,
  Query,
  ParseIntPipe,
  // UsePipes
} from '@nestjs/common';

import { FileService } from './file.service';
import { CreateFileDto } from './dto/create-file.dto';
import { UpdateFileDto } from './dto/update-file.dto';
//导入UseInterceptor装饰器和UploadedFile装饰器
//UseInterceptor用于在Controller中应用拦截器，而UploadedFile用于获取上传的文件
//导入FileInterceptor，是一个处理文件上传的拦截器
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { storage } from './storage';

@ApiTags('文件管理')
@Controller('file')
export class FileController {
  constructor(private readonly fileService: FileService) {}

  //指定接口为Post方法，路径为/upload/file
  @ApiOperation({ summary: '文件上传' })
  @Post('upload')
  // @UsePipes(new FileNameEncodePipe())
  //使用@UseInterceptors()装饰器来应用FileInterceptor拦截器，拦截名字为file的上传文件
  @UseInterceptors(FileInterceptor('file', { storage }))
  //通过@UploadedFile()装饰器，来从request请求中提取出上传的文件
  upload(
    @UploadedFile() file: Express.Multer.File,
    @Body('digest') digest: string,
    @Body('fileName') fileName: string,
  ) {
    //对文件的处理逻辑
    return this.fileService.upload(file, digest, fileName);
  }

  @ApiOperation({ summary: '新增文件记录' })
  @Post()
  create(@Body() createFileDto: CreateFileDto) {
    return this.fileService.create(createFileDto);
  }

  @ApiOperation({ summary: '查询所有文件列表' })
  @Get()
  findAll(
    @Query('page', new ParseIntPipe()) page = 1,
    @Query('pageSize', new ParseIntPipe()) pageSize = 10,
    @Query('name') name = '',
  ) {
    return this.fileService.findAll({ page, pageSize, name });
  }

  @ApiOperation({ summary: '分页查询列表' })
  @Get('page')
  pageSearch(
    @Query('page', new ParseIntPipe()) page = 1,
    @Query('pageSize', new ParseIntPipe()) pageSize = 10,
    @Query('name') name?: string,
  ) {
    return this.fileService.pageSearch({ page, pageSize, name });
  }

  @ApiOperation({ summary: '查询文件详情' })
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.fileService.findOne(id);
  }

  @ApiOperation({ summary: '根据文件md5值获取文件详情' })
  @Get('/digest/:digest')
  getFileByDigest(@Param('digest') digest: string) {
    return this.fileService.getFileByDigest(digest);
  }

  @ApiOperation({ summary: '更新文件数据' })
  @Patch(':id')
  update(@Param('id') id: string, @Body() updateFileDto: UpdateFileDto) {
    return this.fileService.update(id, updateFileDto);
  }

  @ApiOperation({ summary: '删除文件' })
  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.fileService.remove(id);
  }
}
